const express = require('express');
const router = express.Router();
const { userModel, MessageModel, Schoolmodel, ConversationModel } = require('../model/model');
const mongoose = require('mongoose');

// 获取当前学校的用户列表
router.get('/users/:schoolId', async (req, res) => {
    try {
        const { schoolId } = req.params;
        const { currentUserId } = req.query; // 当前登录用户ID，用于排除自己

        // 验证schoolId是否为有效的ObjectId
        if (!mongoose.Types.ObjectId.isValid(schoolId)) {
            return res.json({
                code: 400,
                message: '无效的学校ID格式'
            });
        }

        // 验证学校是否存在
        const school = await Schoolmodel.findById(schoolId);
        if (!school) {
            return res.json({
                code: 404,
                message: '学校不存在'
            });
        }

        // 获取该学校的所有用户，排除当前用户
        const users = await userModel.find({
            schoolId: schoolId,
            _id: { $ne: currentUserId }
        }).select('username studentId avatarImage isAvatarImageSet');

        res.json({
            code: 200,
            message: '获取用户列表成功',
            data: users
        });
    } catch (error) {
        console.error('获取用户列表错误:', error);
        res.json({
            code: 500,
            message: '获取用户列表失败'
        });
    }
});

// 获取或创建聊天会话
router.post('/conversation', async (req, res) => {
    try {
        const { participant1Id, participant2Id } = req.body;

        if (!participant1Id || !participant2Id) {
            return res.json({
                code: 400,
                message: '缺少参与者信息'
            });
        }

        // 验证ObjectId格式
        if (!mongoose.Types.ObjectId.isValid(participant1Id) || !mongoose.Types.ObjectId.isValid(participant2Id)) {
            return res.json({
                code: 400,
                message: '无效的用户ID格式'
            });
        }

        console.log('查找会话，参与者:', { participant1Id, participant2Id });
        
        // 查找现有会话
        let conversation = await ConversationModel.findOne({
            participants: {
                $all: [participant1Id, participant2Id],
                $size: 2
            }
        });

        console.log('找到现有会话:', conversation);

        // 如果不存在则创建新会话
        if (!conversation) {
            console.log('创建新会话，参与者:', [participant1Id, participant2Id]);
            conversation = new ConversationModel({
                participants: [participant1Id, participant2Id]
            });
            await conversation.save();
            console.log('新会话创建成功，ID:', conversation._id);
        }

        res.json({
            code: 200,
            message: '获取会话成功',
            data: conversation
        });
    } catch (error) {
        console.error('获取会话错误:', error);
        res.json({
            code: 500,
            message: '获取会话失败'
        });
    }
});

// 获取聊天记录
router.get('/:conversationId', async (req, res) => {
    try {
        const { conversationId } = req.params;
        const { page = 1, limit = 20 } = req.query;

        console.log('获取聊天记录请求:', { conversationId, page, limit });

        // 验证conversationId格式
        if (!mongoose.Types.ObjectId.isValid(conversationId)) {
            console.log('无效的会话ID格式:', conversationId);
            return res.json({
                code: 400,
                message: '无效的会话ID格式'
            });
        }

        const skip = (page - 1) * limit;

        // 获取会话信息
        const conversation = await ConversationModel.findById(conversationId)
            .populate('participants', 'username studentId avatarImage');

        console.log('找到会话:', conversation);

        if (!conversation) {
            console.log('会话不存在:', conversationId);
            return res.json({
                code: 404,
                message: '会话不存在'
            });
        }

        // 获取会话参与者的ID列表
        const participantIds = conversation.participants.map(p => p._id);
        console.log('会话参与者ID:', participantIds);

        // 查询这个会话中的消息
        // 消息必须是在这两个参与者之间发送的
        const messages = await MessageModel.find({
            $or: [
                // A发送给B的消息
                {
                    senderId: participantIds[0],
                    receiverId: participantIds[1]
                },
                // B发送给A的消息
                {
                    senderId: participantIds[1],
                    receiverId: participantIds[0]
                }
            ]
        })
        .populate('senderId', 'username studentId avatarImage')
        .populate('receiverId', 'username studentId avatarImage')
        .sort({ timestamp: 1 }) // 改为正序，前端会再次排序
        .skip(skip)
        .limit(parseInt(limit));

        console.log('找到消息数量:', messages.length);
        console.log('消息详情:', messages.map(m => ({
            id: m._id,
            senderId: m.senderId._id,
            senderName: m.senderId.username,
            receiverId: m.receiverId._id,
            receiverName: m.receiverId.username,
            content: m.content
        })));

        // 获取总消息数
        const totalMessages = await MessageModel.countDocuments({
            $or: [
                // A发送给B的消息
                {
                    senderId: participantIds[0],
                    receiverId: participantIds[1]
                },
                // B发送给A的消息
                {
                    senderId: participantIds[1],
                    receiverId: participantIds[0]
                }
            ]
        });

        console.log('总消息数:', totalMessages);

        res.json({
            code: 200,
            message: '获取消息记录成功',
            data: {
                conversation,
                messages: messages, // 已经是正序了
                totalMessages,
                hasMore: totalMessages > skip + messages.length
            }
        });
    } catch (error) {
        console.error('获取消息记录错误:', error);
        res.json({
            code: 500,
            message: '获取消息记录失败'
        });
    }
});

// 发送消息
router.post('/', async (req, res) => {
    try {
        const { senderId, receiverId, content, messageType = 'text' } = req.body;

        console.log('发送消息请求:', { senderId, receiverId, content, messageType });

        if (!senderId || !receiverId || !content) {
            return res.json({
                code: 400,
                message: '缺少必要参数'
            });
        }

        // 验证ObjectId格式
        if (!mongoose.Types.ObjectId.isValid(senderId) || !mongoose.Types.ObjectId.isValid(receiverId)) {
            return res.json({
                code: 400,
                message: '无效的用户ID格式'
            });
        }

        // 创建新消息
        const newMessage = new MessageModel({
            senderId,
            receiverId,
            content,
            messageType
        });

        await newMessage.save();
        console.log('消息保存成功:', newMessage._id);

        // 更新或创建会话
        let conversation = await ConversationModel.findOne({
            participants: {
                $all: [senderId, receiverId],
                $size: 2
            }
        });

        if (!conversation) {
            conversation = new ConversationModel({
                participants: [senderId, receiverId],
                lastMessage: newMessage._id,
                lastMessageTime: new Date()
            });
        } else {
            conversation.lastMessage = newMessage._id;
            conversation.lastMessageTime = new Date();
        }

        await conversation.save();
        console.log('会话更新成功');

        // 返回完整的消息信息
        const populatedMessage = await MessageModel.findById(newMessage._id)
            .populate('senderId', 'username studentId avatarImage')
            .populate('receiverId', 'username studentId avatarImage');

        res.json({
            code: 200,
            message: '发送消息成功',
            data: populatedMessage
        });
    } catch (error) {
        console.error('发送消息错误:', error);
        res.json({
            code: 500,
            message: '发送消息失败'
        });
    }
});

// 标记消息为已读
router.put('/read/:conversationId', async (req, res) => {
    try {
        const { conversationId } = req.params;
        const { userId } = req.body;

        // 验证ObjectId格式
        if (!mongoose.Types.ObjectId.isValid(conversationId) || !mongoose.Types.ObjectId.isValid(userId)) {
            return res.json({
                code: 400,
                message: '无效的ID格式'
            });
        }

        // 更新该会话中发给当前用户的所有未读消息
        await MessageModel.updateMany(
            {
                receiverId: userId,
                isRead: false
            },
            {
                isRead: true
            }
        );

        // 更新会话的未读消息数
        const unreadCount = await MessageModel.countDocuments({
            receiverId: userId,
            isRead: false
        });

        await ConversationModel.findByIdAndUpdate(conversationId, {
            unreadCount: unreadCount
        });

        res.json({
            code: 200,
            message: '标记已读成功'
        });
    } catch (error) {
        console.error('标记已读错误:', error);
        res.json({
            code: 500,
            message: '标记已读失败'
        });
    }
});

// 获取用户的聊天会话列表
router.get('/conversations/:userId', async (req, res) => {
    try {
        const { userId } = req.params;

        // 验证userId格式
        if (!mongoose.Types.ObjectId.isValid(userId)) {
            return res.json({
                code: 400,
                message: '无效的用户ID格式'
            });
        }

        const conversations = await ConversationModel.find({
            participants: userId
        })
        .populate('participants', 'username studentId avatarImage')
        .populate('lastMessage')
        .sort({ lastMessageTime: -1 });

        res.json({
            code: 200,
            message: '获取会话列表成功',
            data: conversations
        });
    } catch (error) {
        console.error('获取会话列表错误:', error);
        res.json({
            code: 500,
            message: '获取会话列表失败'
        });
    }
});

module.exports = router; 